package com.shlh.saas.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.shlh.saas.entity.User;
import com.shlh.saas.entity.UserBalance;
import com.shlh.saas.entity.VipPackage;
import com.shlh.saas.mapper.UserBalanceMapper;
import com.shlh.saas.mapper.UserMapper;
import com.shlh.saas.service.UserBalanceService;
import com.shlh.saas.service.VipPackageService;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 用户余额服务实现类
 */
@Service
public class UserBalanceServiceImpl implements UserBalanceService {

    private static final Logger log = LoggerFactory.getLogger(UserBalanceServiceImpl.class);

    @Autowired
    private UserBalanceMapper userBalanceMapper;
    
    @Autowired
    private UserMapper userMapper;

    @Override
    public UserBalance getUserBalance(String phone) {
        return userBalanceMapper.selectByPhone(phone);
    }
    
    @Override
    public UserBalance getUserBalanceById(Long userId) {
        log.debug("通过用户ID查询余额信息: userId={}", userId);
        return userBalanceMapper.selectByUserId(userId);
    }
    
    @Override
    public UserBalance getByUserId(Long userId) {
        log.debug("通过用户ID查询余额信息: userId={}", userId);
        return userBalanceMapper.selectByUserId(userId);
    }

    @Override
    public int updateById(UserBalance userBalance) {
        log.debug("更新用户余额信息: userBalance={}", userBalance);
        return userBalanceMapper.updateById(userBalance);
    }

    @Override
    @Transactional
    public boolean updateUserVip(String phone, Integer vipLevel, Integer months, Integer exportQuota, Integer viewRecords, Integer reverseLookup) {
        log.info("开始更新用户{}的VIP信息，等级:{}，期限:{}个月", phone, vipLevel, months);
        
        // 获取当前用户VIP信息
        UserBalance userBalance = userBalanceMapper.selectByPhone(phone);
        
        int rows = 0;
        
        // 计算VIP到期时间
        LocalDateTime expireDate = null;
        if (vipLevel > 0 && months > 0) {
            // 新的到期时间计算
            LocalDateTime newExpireDate = LocalDateTime.now().plusMonths(months);
            
            // 如果已有套餐，比较新老到期时间
            if (userBalance != null && userBalance.getVipExpireTime() != null) {
                LocalDateTime currentExpireTime = userBalance.getVipExpireTime();
                // 判断当前时间是否已过期
                if (currentExpireTime.isAfter(LocalDateTime.now())) {
                    // 如果当前时间未过期，比较新老到期时间，取较长的
                    if (currentExpireTime.isAfter(newExpireDate)) {
                        // 如果现有到期时间更晚，保留现有到期时间
                        expireDate = currentExpireTime;
                        log.info("用户{}的现有VIP到期时间({})比新计算的到期时间({})更长，保留现有到期时间", 
                            phone, currentExpireTime, newExpireDate);
                    } else {
                        // 如果新到期时间更晚，使用新到期时间
                        expireDate = newExpireDate;
                        log.info("用户{}的新VIP到期时间({})比现有到期时间({})更长，使用新到期时间", 
                            phone, newExpireDate, currentExpireTime);
                    }
                } else {
                    // 如果现有套餐已过期，直接使用新的到期时间
                    expireDate = newExpireDate;
                    log.info("用户{}的现有VIP已过期({}), 设置新的到期时间: {}", phone, currentExpireTime, newExpireDate);
                }
            } else {
                // 如果没有现有套餐，直接使用新的到期时间
                expireDate = newExpireDate;
                log.info("用户{}没有现有VIP，设置新的到期时间: {}", phone, newExpireDate);
            }
        }
        
        // 如果用户余额记录不存在，先创建一条新记录
        if (userBalance == null) {
            log.info("用户{}的余额记录不存在，创建新记录", phone);
            // 先查询用户获取userId
            User user = userMapper.findByPhone(phone);
            if (user == null) {
                log.error("用户{}不存在", phone);
                return false;
            }
            
            UserBalance newBalance = new UserBalance();
            newBalance.setPhone(phone);
            newBalance.setUserId(user.getId());
            newBalance.setVipLevel(vipLevel);
            newBalance.setVipExpireTime(expireDate);
            newBalance.setCashBalance(new BigDecimal("0.00"));
            
            // 设置新套餐的配额
            newBalance.setExportQuotaRemaining(exportQuota);
            newBalance.setViewRecordsRemaining(viewRecords);
            newBalance.setReverseLookupRemaining(reverseLookup);
            newBalance.setEmailSendRemaining(0);
            newBalance.setCreatedAt(LocalDateTime.now());
            newBalance.setUpdatedAt(LocalDateTime.now());
            
            // 插入新记录
            try {
                rows = userBalanceMapper.insert(newBalance);
                log.info("成功为用户{}创建余额记录，影响行数:{}", phone, rows);
            } catch (Exception e) {
                log.error("为用户{}创建余额记录时发生异常:{}", phone, e.getMessage(), e);
                return false;
            }
        } else {
            log.info("用户{}的余额记录已存在，更新VIP信息", phone);
            try {
                // 更新VIP等级
                userBalance.setVipLevel(vipLevel);
                userBalance.setVipExpireTime(expireDate);
                
                // 额度叠加处理
                userBalance.setExportQuotaRemaining(userBalance.getExportQuotaRemaining() + exportQuota);
                userBalance.setViewRecordsRemaining(userBalance.getViewRecordsRemaining() + viewRecords);
                userBalance.setReverseLookupRemaining(userBalance.getReverseLookupRemaining() + reverseLookup);
                userBalance.setUpdatedAt(LocalDateTime.now());
                
                log.info("用户{}的VIP额度更新 - 导出配额:{}+{}={}, 查看配额:{}+{}={}, 反查配额:{}+{}={}",
                    phone,
                    userBalance.getExportQuotaRemaining() - exportQuota, exportQuota, userBalance.getExportQuotaRemaining(),
                    userBalance.getViewRecordsRemaining() - viewRecords, viewRecords, userBalance.getViewRecordsRemaining(),
                    userBalance.getReverseLookupRemaining() - reverseLookup, reverseLookup, userBalance.getReverseLookupRemaining());
                
                rows = userBalanceMapper.updateById(userBalance);
                log.info("成功更新用户{}的VIP信息，影响行数:{}", phone, rows);
            } catch (Exception e) {
                log.error("更新用户{}的VIP信息时发生异常:{}", phone, e.getMessage(), e);
                return false;
            }
        }
        
        return rows > 0;
    }
    
    @Override
    @Transactional
    public boolean updateUserVipById(Long userId, Integer vipLevel, Integer months, Integer exportQuota, Integer viewRecords, Integer reverseLookup) {
        log.info("开始更新用户ID={}的VIP信息，等级:{}，期限:{}个月", userId, vipLevel, months);
        
        // 查询用户信息
        User user = userMapper.selectById(userId);
        if (user == null) {
            log.error("用户ID={}不存在", userId);
            return false;
        }
        
        // 获取当前用户VIP信息
        UserBalance userBalance = userBalanceMapper.selectByUserId(userId);
        
        int rows = 0;

        // 计算VIP到期时间
        LocalDateTime expireDate = null;
        if (vipLevel > 0 && months > 0) {
            // 新的到期时间计算
            LocalDateTime newExpireDate = LocalDateTime.now().plusMonths(months);
            
            // 如果已有套餐，比较新老到期时间
            if (userBalance != null && userBalance.getVipExpireTime() != null) {
                LocalDateTime currentExpireTime = userBalance.getVipExpireTime();
                // 判断当前时间是否已过期
                if (currentExpireTime.isAfter(LocalDateTime.now())) {
                    // 如果当前时间未过期，比较新老到期时间，取较长的
                    if (currentExpireTime.isAfter(newExpireDate)) {
                        // 如果现有到期时间更晚，保留现有到期时间
                        expireDate = currentExpireTime;
                        log.info("用户ID={}的现有VIP到期时间({})比新计算的到期时间({})更长，保留现有到期时间", 
                            userId, currentExpireTime, newExpireDate);
                    } else {
                        // 如果新到期时间更晚，使用新到期时间
                        expireDate = newExpireDate;
                        log.info("用户ID={}的新VIP到期时间({})比现有到期时间({})更长，使用新到期时间", 
                            userId, newExpireDate, currentExpireTime);
                    }
                } else {
                    // 如果现有套餐已过期，直接使用新的到期时间
                    expireDate = newExpireDate;
                    log.info("用户ID={}的现有VIP已过期({}), 设置新的到期时间: {}", userId, currentExpireTime, newExpireDate);
                }
            } else {
                // 如果没有现有套餐，直接使用新的到期时间
                expireDate = newExpireDate;
                log.info("用户ID={}没有现有VIP，设置新的到期时间: {}", userId, newExpireDate);
            }
        }
        
        // 如果用户余额记录不存在，先创建一条新记录
        if (userBalance == null) {
            log.info("用户ID={}的余额记录不存在，创建新记录", userId);
            UserBalance newBalance = new UserBalance();
            newBalance.setPhone(user.getPhone());
            newBalance.setUserId(userId);
            newBalance.setVipLevel(vipLevel);
            newBalance.setVipExpireTime(expireDate);
            newBalance.setCashBalance(new BigDecimal("0.00"));
            
            // 设置新套餐的配额
            newBalance.setExportQuotaRemaining(exportQuota);
            newBalance.setViewRecordsRemaining(viewRecords);
            newBalance.setReverseLookupRemaining(reverseLookup);
            newBalance.setEmailSendRemaining(0);
            newBalance.setCreatedAt(LocalDateTime.now());
            newBalance.setUpdatedAt(LocalDateTime.now());
            
            // 插入新记录
            try {
                rows = userBalanceMapper.insert(newBalance);
                log.info("成功为用户ID={}创建余额记录，影响行数:{}", userId, rows);
            } catch (Exception e) {
                log.error("为用户ID={}创建余额记录时发生异常:{}", userId, e.getMessage(), e);
                return false;
            }
        } else {
            log.info("用户ID={}的余额记录已存在，更新VIP信息", userId);
            try {
                // 更新VIP等级
                userBalance.setVipLevel(vipLevel);
                userBalance.setVipExpireTime(expireDate);
                
                // 额度叠加处理
                userBalance.setExportQuotaRemaining(userBalance.getExportQuotaRemaining() + exportQuota);
                userBalance.setViewRecordsRemaining(userBalance.getViewRecordsRemaining() + viewRecords);
                userBalance.setReverseLookupRemaining(userBalance.getReverseLookupRemaining() + reverseLookup);
                userBalance.setUpdatedAt(LocalDateTime.now());
                
                log.info("用户ID={}的VIP额度更新 - 导出配额:{}+{}={}, 查看配额:{}+{}={}, 反查配额:{}+{}={}",
                    userId,
                    userBalance.getExportQuotaRemaining() - exportQuota, exportQuota, userBalance.getExportQuotaRemaining(),
                    userBalance.getViewRecordsRemaining() - viewRecords, viewRecords, userBalance.getViewRecordsRemaining(),
                    userBalance.getReverseLookupRemaining() - reverseLookup, reverseLookup, userBalance.getReverseLookupRemaining());
                
                rows = userBalanceMapper.updateById(userBalance);
                log.info("成功更新用户ID={}的VIP信息，影响行数:{}", userId, rows);
            } catch (Exception e) {
                log.error("更新用户ID={}的VIP信息时发生异常:{}", userId, e.getMessage(), e);
                return false;
            }
        }
        
        return rows > 0;
    }

    @Override
    public boolean increaseEmailQuota(String phone, Integer count) {
        int rows = userBalanceMapper.increaseEmailQuota(phone, count);
        return rows > 0;
    }
    
    @Override
    public boolean increaseEmailQuotaById(Long userId, Integer count) {
        int rows = userBalanceMapper.increaseEmailQuotaById(userId, count);
        return rows > 0;
    }
    
    @Override
    public boolean updateEmailPackageLevel(String phone, Integer packageLevel) {
        log.info("开始更新用户{}的邮件套餐等级为{}", phone, packageLevel);
        
        // 获取当前用户余额信息
        UserBalance userBalance = userBalanceMapper.selectByPhone(phone);
        
        int rows = 0;
        
        // 如果用户余额记录不存在，先创建一条新记录
        if (userBalance == null) {
            log.info("用户{}的余额记录不存在，创建新记录", phone);
            // 先查询用户获取userId
            User user = userMapper.findByPhone(phone);
            if (user == null) {
                log.error("用户{}不存在", phone);
                return false;
            }
            
            UserBalance newBalance = new UserBalance();
            newBalance.setPhone(phone);
            newBalance.setUserId(user.getId());
            newBalance.setVipLevel(0); // 默认免费版
            newBalance.setEmailPackageLevel(packageLevel); // 设置邮件套餐等级
            newBalance.setCashBalance(new BigDecimal("0.00"));
            newBalance.setExportQuotaRemaining(0);
            newBalance.setViewRecordsRemaining(5); // 免费版默认5次
            newBalance.setReverseLookupRemaining(0);
            newBalance.setEmailSendRemaining(0); // 邮件配额会在increaseEmailQuota方法中增加
            newBalance.setCreatedAt(LocalDateTime.now());
            newBalance.setUpdatedAt(LocalDateTime.now());
            
            // 插入新记录
            try {
                rows = userBalanceMapper.insert(newBalance);
                log.info("成功为用户{}创建余额记录并设置邮件套餐等级为{}，影响行数:{}", phone, packageLevel, rows);
            } catch (Exception e) {
                log.error("为用户{}创建余额记录时发生异常:{}", phone, e.getMessage(), e);
                return false;
            }
        } else {
            // 更新用户邮件套餐等级
            try {
                // 使用自定义方法更新用户邮件套餐等级
                rows = userBalanceMapper.updateEmailPackageLevel(phone, packageLevel);
                log.info("成功更新用户{}的邮件套餐等级为{}，影响行数:{}", phone, packageLevel, rows);
            } catch (Exception e) {
                log.error("更新用户{}的邮件套餐等级时发生异常:{}", phone, e.getMessage(), e);
                return false;
            }
        }
        
        return rows > 0;
    }
    
    @Override
    public boolean updateEmailPackageLevelById(Long userId, Integer packageLevel) {
        log.info("开始更新用户ID={}的邮件套餐等级为{}", userId, packageLevel);
        
        // 查询用户信息
        User user = userMapper.selectById(userId);
        if (user == null) {
            log.error("用户ID={}不存在", userId);
            return false;
        }
        
        // 获取当前用户余额信息
        UserBalance userBalance = userBalanceMapper.selectByUserId(userId);
        
        int rows = 0;
        
        // 如果用户余额记录不存在，先创建一条新记录
        if (userBalance == null) {
            log.info("用户ID={}的余额记录不存在，创建新记录", userId);
            UserBalance newBalance = new UserBalance();
            newBalance.setPhone(user.getPhone());
            newBalance.setUserId(userId);
            newBalance.setVipLevel(0); // 默认免费版
            newBalance.setEmailPackageLevel(packageLevel); // 设置邮件套餐等级
            newBalance.setCashBalance(new BigDecimal("0.00"));
            newBalance.setExportQuotaRemaining(0);
            newBalance.setViewRecordsRemaining(5); // 免费版默认5次
            newBalance.setReverseLookupRemaining(0);
            newBalance.setEmailSendRemaining(0); // 邮件配额会在increaseEmailQuota方法中增加
            newBalance.setCreatedAt(LocalDateTime.now());
            newBalance.setUpdatedAt(LocalDateTime.now());
            
            // 插入新记录
            try {
                rows = userBalanceMapper.insert(newBalance);
                log.info("成功为用户ID={}创建余额记录并设置邮件套餐等级为{}，影响行数:{}", userId, packageLevel, rows);
            } catch (Exception e) {
                log.error("为用户ID={}创建余额记录时发生异常:{}", userId, e.getMessage(), e);
                return false;
            }
        } else {
            // 更新用户邮件套餐等级
            try {
                // 使用自定义方法更新用户邮件套餐等级
                rows = userBalanceMapper.updateEmailPackageLevelById(userId, packageLevel);
                log.info("成功更新用户ID={}的邮件套餐等级为{}，影响行数:{}", userId, packageLevel, rows);
            } catch (Exception e) {
                log.error("更新用户ID={}的邮件套餐等级时发生异常:{}", userId, e.getMessage(), e);
                return false;
            }
        }
        
        return rows > 0;
    }
    
    /**
     * 同步用户余额记录，确保每个users表中的用户在user_balances表中都有对应记录
     * 每天凌晨2点执行一次
     */
    @Override
    @Scheduled(cron = "0 0 2 * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void syncUserBalances() {
        log.info("开始同步用户余额记录...");
        int total = 0;
        int success = 0;
        
        try {
            // 获取所有用户
            List<User> allUsers = userMapper.selectList(new LambdaQueryWrapper<User>()
                    .eq(User::getIsDeleted, 0));
            total = allUsers.size();
            log.info("获取到{}个有效用户", total);
            
            for (User user : allUsers) {
                if (user.getPhone() == null || user.getPhone().isEmpty()) {
                    log.warn("用户ID={}的手机号为空，跳过同步", user.getId());
                    continue;
                }
                
                // 检查用户是否已有余额记录
                UserBalance existingBalance = userBalanceMapper.selectByUserId(user.getId());
                if (existingBalance != null) {
                    continue; // 已有记录，跳过
                }
                
                // 创建默认余额记录
                UserBalance newBalance = new UserBalance();
                newBalance.setPhone(user.getPhone());
                newBalance.setUserId(user.getId());
                newBalance.setVipLevel(0); // 默认免费版
                
                newBalance.setCashBalance(new BigDecimal("0.00")); // 默认余额为0
                
                // 根据会员等级设置配额
                switch (newBalance.getVipLevel()) {
                    case 1: // 初级VIP
                        newBalance.setExportQuotaRemaining(100);
                        newBalance.setViewRecordsRemaining(10);
                        newBalance.setReverseLookupRemaining(20);
                        break;
                    case 2: // 高级VIP
                        newBalance.setExportQuotaRemaining(300);
                        newBalance.setViewRecordsRemaining(30);
                        newBalance.setReverseLookupRemaining(50);
                        break;
                    case 3: // 尊享VIP
                        newBalance.setExportQuotaRemaining(1000);
                        newBalance.setViewRecordsRemaining(100);
                        newBalance.setReverseLookupRemaining(100);
                        break;
                    default: // 免费版
                        newBalance.setExportQuotaRemaining(0);
                        newBalance.setViewRecordsRemaining(5);
                        newBalance.setReverseLookupRemaining(0);
                }
                
                newBalance.setEmailSendRemaining(0);
                newBalance.setCreatedAt(LocalDateTime.now());
                newBalance.setUpdatedAt(LocalDateTime.now());
                
                // 插入余额记录
                try {
                    int rows = userBalanceMapper.insert(newBalance);
                    if (rows > 0) {
                        success++;
                        log.info("为用户ID={}创建余额记录成功", user.getId());
                    } else {
                        log.warn("为用户ID={}创建余额记录失败", user.getId());
                    }
                } catch (Exception e) {
                    log.error("为用户ID={}创建余额记录时发生异常: {}", user.getId(), e.getMessage(), e);
                }
            }
            
            log.info("用户余额记录同步完成，总用户: {}，成功创建: {}", total, success);
        } catch (Exception e) {
            log.error("同步用户余额记录时发生异常: {}", e.getMessage(), e);
        }
    }

    @Override
    @Transactional
    public BigDecimal addBalance(Long userId, BigDecimal amount) {
        if (amount.compareTo(BigDecimal.ZERO) <= 0) {
            throw new IllegalArgumentException("增加的金额必须大于0");
        }
        
        UserBalance userBalance = userBalanceMapper.selectByUserId(userId);
        if (userBalance == null) {
            // 获取用户信息
            User user = userMapper.selectById(userId);
            if (user == null) {
                throw new RuntimeException("用户不存在");
            }
            
            // 创建新的用户余额记录
            userBalance = new UserBalance();
            userBalance.setUserId(userId);
            userBalance.setPhone(user.getPhone());
            userBalance.setCashBalance(amount);
            userBalance.setVipLevel(0);
            userBalance.setExportQuotaRemaining(0);
            userBalance.setViewRecordsRemaining(5); // 默认给5次查询机会
            userBalance.setReverseLookupRemaining(0);
            userBalance.setEmailSendRemaining(0);
            userBalance.setCreatedAt(LocalDateTime.now());
            userBalance.setUpdatedAt(LocalDateTime.now());
            
            userBalanceMapper.insert(userBalance);
            return amount;
        } else {
            // 更新余额
            BigDecimal newBalance = userBalance.getCashBalance().add(amount);
            userBalance.setCashBalance(newBalance);
            userBalance.setUpdatedAt(LocalDateTime.now());
            
            userBalanceMapper.updateById(userBalance);
            return newBalance;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deductViewRecords(Long userId, Integer count) {
        log.info("开始扣除用户ID={}的查看记录余额，数量:{}", userId, count);
        
        if (count <= 0) {
            log.warn("扣除的查看记录数量必须大于0");
            return false;
        }
        
        // 获取当前用户余额信息
        UserBalance userBalance = userBalanceMapper.selectByUserId(userId);
        if (userBalance == null) {
            log.error("用户ID={}的余额记录不存在", userId);
            return false;
        }
        
        // 检查余额是否足够
        if (userBalance.getViewRecordsRemaining() < count) {
            log.warn("用户ID={}的查看记录余额不足，当前余额:{}，需要扣除:{}", userId, userBalance.getViewRecordsRemaining(), count);
            return false;
        }
        
        try {
            // 更新余额
            int remainingCount = userBalance.getViewRecordsRemaining() - count;
            userBalance.setViewRecordsRemaining(remainingCount);
            userBalance.setUpdatedAt(LocalDateTime.now());
            
            int rows = userBalanceMapper.updateById(userBalance);
            log.info("成功扣除用户ID={}的查看记录余额，影响行数:{}，当前余额:{}", userId, rows, remainingCount);
            return rows > 0;
        } catch (Exception e) {
            log.error("扣除用户ID={}的查看记录余额时发生异常:{}", userId, e.getMessage(), e);
            throw e;
        }
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deductExportQuota(Long userId, Integer count) {
        log.info("开始扣除用户ID={}的导出次数余额，数量:{}", userId, count);
        
        if (count <= 0) {
            log.warn("扣除的导出次数必须大于0");
            return false;
        }
        
        // 获取当前用户余额信息
        UserBalance userBalance = userBalanceMapper.selectByUserId(userId);
        if (userBalance == null) {
            log.error("用户ID={}的余额记录不存在", userId);
            return false;
        }
        
        // 检查余额是否足够
        if (userBalance.getExportQuotaRemaining() < count) {
            log.warn("用户ID={}的导出次数余额不足，当前余额:{}，需要扣除:{}", userId, userBalance.getExportQuotaRemaining(), count);
            return false;
        }
        
        try {
            // 更新余额
            int remainingCount = userBalance.getExportQuotaRemaining() - count;
            userBalance.setExportQuotaRemaining(remainingCount);
            userBalance.setUpdatedAt(LocalDateTime.now());
            
            int rows = userBalanceMapper.updateById(userBalance);
            log.info("成功扣除用户ID={}的导出次数余额，影响行数:{}，当前余额:{}", userId, rows, remainingCount);
            return rows > 0;
        } catch (Exception e) {
            log.error("扣除用户ID={}的导出次数余额时发生异常:{}", userId, e.getMessage(), e);
            throw e;
        }
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deductReverseLookup(Long userId, Integer count) {
        log.info("开始扣除用户ID={}的反查次数余额，数量:{}", userId, count);
        
        if (count <= 0) {
            log.warn("扣除的反查次数必须大于0");
            return false;
        }
        
        // 获取当前用户余额信息
        UserBalance userBalance = userBalanceMapper.selectByUserId(userId);
        if (userBalance == null) {
            log.error("用户ID={}的余额记录不存在", userId);
            return false;
        }
        
        // 检查余额是否足够
        if (userBalance.getReverseLookupRemaining() < count) {
            log.warn("用户ID={}的反查次数余额不足，当前余额:{}，需要扣除:{}", userId, userBalance.getReverseLookupRemaining(), count);
            return false;
        }
        
        try {
            // 更新余额
            int remainingCount = userBalance.getReverseLookupRemaining() - count;
            userBalance.setReverseLookupRemaining(remainingCount);
            userBalance.setUpdatedAt(LocalDateTime.now());
            
            int rows = userBalanceMapper.updateById(userBalance);
            log.info("成功扣除用户ID={}的反查次数余额，影响行数:{}，当前余额:{}", userId, rows, remainingCount);
            return rows > 0;
        } catch (Exception e) {
            log.error("扣除用户ID={}的反查次数余额时发生异常:{}", userId, e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public boolean updateEmailPackageExpireTimeById(Long userId, LocalDateTime expireTime) {
        log.info("开始更新用户ID={}的邮件套餐过期时间为{}", userId, expireTime);
        
        // 获取当前用户余额信息
        UserBalance userBalance = userBalanceMapper.selectByUserId(userId);
        
        int rows = 0;
        
        // 如果用户余额记录不存在，先创建一条新记录
        if (userBalance == null) {
            log.info("用户ID={}的余额记录不存在，创建新记录", userId);
            // 查询用户信息
            User user = userMapper.selectById(userId);
            if (user == null) {
                log.error("用户ID={}不存在", userId);
                return false;
            }
            
            UserBalance newBalance = new UserBalance();
            newBalance.setPhone(user.getPhone());
            newBalance.setUserId(userId);
            newBalance.setVipLevel(0); // 默认免费版
            newBalance.setEmailPackageLevel(1); // 设置默认邮件套餐等级
            newBalance.setEmailPackageExpireTime(expireTime); // 设置邮件套餐过期时间
            newBalance.setCashBalance(new BigDecimal("0.00"));
            newBalance.setExportQuotaRemaining(0);
            newBalance.setViewRecordsRemaining(5); // 免费版默认5次
            newBalance.setReverseLookupRemaining(0);
            newBalance.setEmailSendRemaining(0);
            newBalance.setCreatedAt(LocalDateTime.now());
            newBalance.setUpdatedAt(LocalDateTime.now());
            
            // 插入新记录
            try {
                rows = userBalanceMapper.insert(newBalance);
                log.info("成功为用户ID={}创建余额记录并设置邮件套餐过期时间为{}，影响行数:{}", userId, expireTime, rows);
            } catch (Exception e) {
                log.error("为用户ID={}创建余额记录时发生异常:{}", userId, e.getMessage(), e);
                return false;
            }
        } else {
            log.info("用户ID={}的余额记录已存在，更新邮件套餐过期时间", userId);
            try {
                // 更新邮件套餐过期时间
                userBalance.setEmailPackageExpireTime(expireTime);
                userBalance.setUpdatedAt(LocalDateTime.now());
                
                rows = userBalanceMapper.updateById(userBalance);
                log.info("成功更新用户ID={}的邮件套餐过期时间为{}，影响行数:{}", userId, expireTime, rows);
            } catch (Exception e) {
                log.error("更新用户ID={}的邮件套餐过期时间时发生异常:{}", userId, e.getMessage(), e);
                return false;
            }
        }
        
        return rows > 0;
    }
}